package com.jz.main.io.nio;

import java.time.Instant;

public class LeakyBucket {
    private final int capacity; // 漏桶容量
    private int water; // 漏桶当前水量
    private long lastLeakTime; // 上次漏水时间
    private final long leakIntervalMs; // 漏水时间间隔（毫秒）

    public LeakyBucket(int capacity, long leakRatePerMs) {
        this.capacity = capacity;
        this.water = 0;
        this.lastLeakTime = Instant.now().toEpochMilli();
        this.leakIntervalMs = leakRatePerMs;
    }

    public synchronized boolean allowRequest() {
        long currentTime = Instant.now().toEpochMilli();
        long elapsedTime = currentTime - lastLeakTime;
        lastLeakTime = currentTime;

        // 水先漏一段时间
        water -= elapsedTime * leakIntervalMs;
        if (water < 0) {
            water = 0;
        }

        // 若请求成功则加水，否则拒绝
        if (water + 1 <= capacity) {
            water += 1;
            return true;  // 允许请求通过
        } else {
            return false; // 请求被限流
        }
    }

    public static void main(String[] args) {
        LeakyBucket leakyBucket = new LeakyBucket(10, 1000); // 定义一个容量为 10，每秒漏水速率为 1000 ms 的漏桶

        for (int i = 0; i < 20; i++) {
            if (leakyBucket.allowRequest()) {
                System.out.println("Request " + i + ": Allowed");
            } else {
                System.out.println("Request " + i + ": Rejected");
            }
        }
    }
}
